package com.yun.app.gateway.filter;

import com.yun.app.gateway.config.WhiteListProperties;
import com.yun.app.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * @description: 登录校验过滤器
 * @author: yu
 * @data 2025年07月17日 10:23
 */
@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final WhiteListProperties whiteListProperties;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 获取前端传输的路径
        String path = request.getURI().getPath();

        // 1.校验登录路径
        // 1.1登录路径直接放行
        if (whiteListProperties.getPaths().stream().anyMatch(white -> antPathMatcher.match(white, path))) {
            return chain.filter(exchange);
        }
        // 1.2非登录路径继续判断
        // 2.判断是否具有token
        String token = request.getHeaders().getFirst("token");

        if (StringUtils.isEmpty(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);// 401没有权限
            return response.setComplete();
        }

        // 3.判断token是否过期
        Claims claims = AppJwtUtil.getClaimsBody(token);
        int i = AppJwtUtil.verifyToken(claims);

        if (i == 1 || i == 2) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);// 401没有权限
            return response.setComplete();
        }

        // 4.将token解析出的信息传递给微服务
        String userInfo = String.valueOf(claims.get("id")); // ✅ 推荐写法

        exchange = exchange.mutate()
                .request(builder -> builder.header("user-info", userInfo))
                .build();

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
